package com.example.customizeview;

import androidx.appcompat.app.AppCompatActivity;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;

public class TestBitmapSize extends AppCompatActivity {
    private static final String TAG = "TestBitmapSize";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.test_200_200);
        Log.i(TAG, "onCreate: originBitmap " + bitmap.getByteCount());
        Bitmap sampledBitmap = decodeSampledBitmapFromResource(getResources(), R.drawable.test_200_200, 50, 50);
        Log.i(TAG, "onCreate: sampledBitmap " + sampledBitmap.getByteCount());
    }

    public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId, int reqWidth, int reqHeight) {
        // 检查bitmap的大小
        final BitmapFactory.Options options = new BitmapFactory.Options();
        // 设置为true，BitmapFactory会解析图片的原始宽高信息，并不会加载图片
        options.inJustDecodeBounds = true;

        BitmapFactory.decodeResource(res, resId, options);

        // 计算采样率
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

        // 设置为false，加载bitmap
        options.inJustDecodeBounds = false;

        return BitmapFactory.decodeResource(res, resId, options);
    }

    private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        int width = options.outWidth;
        int height = options.outHeight;
        Log.i(TAG, "calculateInSampleSize: out width and height is " + width + " height " + height);
        int inSampleWidth = 1;
        if (height > reqHeight || width > reqWidth) {
            int halfHeight = height / 2;
            int halfWidth = width / 2;

            // 采样率设置为2的指数
            while ((halfHeight / inSampleWidth) >= reqHeight && (halfWidth / inSampleWidth) >= reqWidth) {
                inSampleWidth *= 2;
            }
        }
        return inSampleWidth;
    }
}
